package com.example.security.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author : zhayh
 * @date : 2021-4-18 17:59
 * @description : 自定义令牌校验
 */

@Component
public class UserTokenFilter extends GenericFilterBean {
    @Resource
    private TokenProvider tokenProvider;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        // 1、从请求头部找到令牌
        String token = httpServletRequest.getHeader("Authorization");
        if (token == null) {
            // 如果请求头部没有，从查询参数中找到令牌
            token = httpServletRequest.getParameter("Authorization");
        }
        if (token != null) {
            // 2、使用TokenProvider校验这个token合法性
            if (tokenProvider.validateToken(token)) {
                // 3、token校验通过，通过token工具类将token转为Authentication
                Authentication user = tokenProvider.getUser(token);
                // 4、将用户交给SpringSecurity管理
                SecurityContextHolder.getContext().setAuthentication(user);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
